import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/modules/auth'

const instance = axios.create({
  baseURL: 'http://127.0.0.1:8000/api',
  timeout: 10000
})

instance.interceptors.request.use(
  (config) => {
    const authStore = useAuthStore()
    if (authStore.token) {
      config.headers.Authorization = `Bearer ${authStore.token}`
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    return res.data
  },
  (err) => {
    const authStore = useAuthStore()

    if (err.response?.status === 401) {
      authStore.logout()
      window.location.href = '/login'
    } else {
      ElMessage.error(err.response?.data?.message || '请求失败')
    }

    return Promise.reject(err)
  }
)

export default instance
